<template>
  <a-drawer
    :width="500"
    :visible="show"
    :footer="false"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> {{ data?.type }}组件编辑 </template>
    <div class="seting-box">
      <p class="item-title">组件宽度</p>
      <a-select
        :style="{ width: '320px', background: '#ffffff' }"
        v-model="data.width"
        placeholder="请选择"
        allow-clear
      >
        <a-option value="default">默认</a-option>
        <a-option value="small">小</a-option>
        <a-option value="middle">中</a-option>
        <a-option value="max">大</a-option>
      </a-select>
      <p class="item-title">背景色</p>
      <a-select
        :style="{ width: '320px', background: '#ffffff' }"
        v-model="data.bgColor"
        placeholder="Please select ..."
      >
        <a-option value="#ffffff">白色</a-option>
        <a-option value="#f8f9fa">灰色</a-option>
      </a-select>
      <p class="item-title">桌面显示的列数（最小：1，最大：4）</p>
      <a-slider
        v-model="data.row"
        :min="1"
        :max="4"
        :default-value="3"
        show-input
      />
      <p class="item-title">移动端显示的列数（最小：1，最大：2）</p>
      <a-slider
        v-model="data.mobileRow"
        :min="1"
        :max="2"
        :default-value="2"
        show-input
      />
      <p class="item-title">文章</p>
      <div v-if="data.list.length === 0">暂无数据</div>
      <template v-if="data.list.length">
        <draggable
          v-model="data.list"
          :component-data="{
            tag: 'div',
            type: 'transition-group',
            name: !drag ? 'flip-list' : null,
          }"
          v-bind="linkDragOptions"
          :disabled="false"
          @start="drag = true"
          @end="drag = false"
          item-key="key"
        >
          <template #item="{ element: link, index: sectionIndex }">
            <div class="draggable_box">
              <div class="drag_top_box">
                <div @click="toggleCollapse(link)">
                  <icon-drag-dot style="margin-right: 10px" />{{ link.title }}
                </div>
                <div>
                  <icon-drag-arrow class="icon_drag" />
                  <icon-delete
                    class="btn-delete"
                    @click.stop="handleDelete(link.key)"
                  />
                </div>
              </div>
              <transition name="collapse">
                <div v-show="!isCollapsed(link)">
                  <h2>照片</h2>
                  <p class="item-title">标题</p>
                  <a-input
                    v-model="link.title"
                    placeholder="请输入标题"
                    allow-clear
                  />
                  <p class="item-title">图片</p>
                  <img class="item-img" :src="link.image" />
                  <div class="item-uplaod flex items-center">
                    <a-input
                      v-model="link.image"
                      placeholder="请输入图片链接"
                      allow-clear
                    />
                    <Upload
                      v-model="link.image"
                      name="BannerPage"
                      button-class="fit-content"
                    />
                  </div>
                  <p class="item-title">网址</p>
                  <a-input
                    v-model="link.link"
                    placeholder="请输入网址"
                    allow-clear
                  />
                  <p class="item-title">标签名称</p>
                  <a-input
                    v-model="link.labelName"
                    placeholder="请输入标签名称"
                    allow-clear
                  />
                  <p class="item-title">描述</p>
                  <a-input
                    v-model="link.desc"
                    placeholder="请输入描述"
                    allow-clear
                  />
                  <p class="item-title">日期</p>
                  <a-date-picker
                    v-model="link.date"
                    style="width: 200px; background: #ffffff"
                  />
                </div>
              </transition>
            </div>
          </template>
        </draggable>
      </template>
      <div class="btn_group">
        <a-button
          @click="handleAdd('prepend')"
          type="primary"
          style="margin-right: 20px"
          >前置</a-button
        >
        <a-button @click="handleAdd('append')" type="primary">追加</a-button>
      </div>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { randomString } from "@/utils/common";
import Upload from "@/common/Upload/index.vue";
import { ref, computed, watch, defineAsyncComponent } from "vue";

// 动态导入 draggable，避免 SSR 问题
const draggable = defineAsyncComponent(() => import("vuedraggable"));

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },

  data: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:show"]);
const linkDragOptions = computed(() => ({
  animation: 200,
  group: "links", // 链接专用分组
  disabled: false,
  ghostClass: "ghost",
}));

const handleCancel = () => {
  emit("update:show", false);
};
const drag = ref(false);
const collapsedItems = ref(new Set());
// 切换指定项的折叠状态
const toggleCollapse = (item: any) => {
  // 如果当前项目已经展开，则折叠它
  if (!collapsedItems.value.has(item.key)) {
    collapsedItems.value.add(item.key);
  } else {
    // 如果当前项目是折叠的，则展开它并折叠所有其他项目
    // 首先获取所有章节的key
    const allSectionKeys: string[] = [];
    props.data.list.forEach((section: any) => {
      if (section.key) {
        allSectionKeys.push(section.key);
      }
    });

    // 将所有章节设为折叠状态
    collapsedItems.value = new Set(allSectionKeys);
    // 然后展开当前点击的章节
    collapsedItems.value.delete(item.key);
  }
};
const handleDelete = (key: string) => {
  props.data.list = props.data.list.filter((item: any) => item.key !== key);
};
// 检查指定项是否已折叠
const isCollapsed = (item: any) => {
  return collapsedItems.value.has(item.key);
};
const isInit = ref(false);
watch(
  () => props.data?.list,
  (newSections: any) => {
    if (newSections && Array.isArray(newSections) && !isInit.value) {
      isInit.value = true;
      // 将所有sections的key添加到collapsedItems中，实现默认折叠
      const allKeys = newSections.map((section) => section.key);
      collapsedItems.value = new Set(allKeys);
    }
  },
  { immediate: true, deep: true }
);
const handleAdd = (dir: string) => {
  const newItem = {
    // key: randomString(8),
    // title: "新文章",
    // description: "这是一个新的文章描述",
    // image: "https://picsum.photos/800/600",
    // date: new Date().toISOString().split("T")[0],
    // label: "new",
    // labelName: "新标签",
    // category: "new",
    key: randomString(8),
    title: "示例",
    desc: "描述",
    date: "2024-03-08",
    category: "news",
    link: "https://www.baidu.com",
    labelName: "NEWS",
    image:
      "https://images.unsplash.com/photo-1677442136019-21780ecad995?w=800&h=600&fit=crop",
    alt: "人工智能概念图",
  };
  // 使用重新赋值以触发引用变化，从而让父组件的 watch(list) 响应
  if (dir === "prepend") {
    props.data.list = [newItem, ...(props.data.list || [])];
  } else if (dir === "append") {
    props.data.list = [...(props.data.list || []), newItem];
  }
};
</script>

<style lang="scss" scoped>
.btn-delete {
  padding: 4px;
  font-size: 24px;
  cursor: pointer;
}
.icon_drag {
  padding: 4px;
  font-size: 24px;
  cursor: pointer;
  &:hover {
    opacity: 0.8;
  }
}
.item-img {
  height: 100px;
}
.seting-box {
  padding: 20px;
  background: #f0f2f5;
  border-radius: 3px;
  .arco-input-wrapper {
    background: #ffffff;
  }
  .arco-picker {
    background: #fff;
  }
}
.setting-content {
  .setting-header {
    padding-bottom: 12px;

    .header-title {
      width: 120px;
      padding-right: 12px;
      text-align: right;
    }
  }

  .setting-body {
    margin-top: 12px;

    .setting-item {
      position: relative;
      padding: 16px 12px;
      background: #f0f2f5;
      border-radius: 8px;
      margin-bottom: 20px;

      .btn-group {
        position: absolute;
        right: 0;
        top: 0;
        display: flex;
        align-items: center;
        padding: 4px;

        .btn-delete {
          padding: 4px;
          font-size: 24px;
          cursor: pointer;
        }
      }

      .item-name {
        font-size: 16px;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 1px solid #fff;
      }

      .item-title {
        padding: 12px 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }

      .arco-input-wrapper {
        background: #fff;
      }

      .item-button {
        position: relative;
        padding: 12px 8px 4px;
        background: #fff;
        border-radius: 4px;
        margin: 4px 0;
        transition: all 0.3s ease;

        &.draggable-item {          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
          }

          // 当禁用拖拽时，不显示拖拽效果
          &.sortable-disabled {
            cursor: default;

            &:hover {
              box-shadow: none;
              transform: none;
            }
          }
        }

        .arco-input-wrapper {
          background: #f2f3f5;
        }
      }

      // 拖拽相关样式
      .flip-list-move {
        transition: transform 0.5s;
      }

      .no-move {
        transition: transform 0s;
      }

      .ghost {
        opacity: 0.5;
        background: #c8ebfb;
      }

      .list-group {
        min-height: 20px;
      }

      .list-group-item {      }

      .list-group-item i {
        cursor: pointer;
      }

      .item-action {
        padding: 10px 0;

        .action-text {
          width: 150px;
          margin-right: 8px;
        }
      }

      .item-add-btn {
        display: inline-block;
        padding: 2px 8px;
        margin-top: 5px;
        font-size: 11px;
        color: #165dff;
        border-radius: 4px;
        font-weight: 600;
        border: 1px solid #165dff;
        cursor: pointer;
      }

      .item-img {
        margin-top: 12px;
        height: 160px;
      }

      .fit-content {
        width: fit-content;
      }

      .item-img-list {
        .img-list-item {
          margin: 4px 0;
          position: relative;
          padding: 8px;
          border-radius: 4px;
          transition: all 0.3s ease;
          background: #fff;
          border-radius: 4px;

          &.draggable-item {            &:hover {
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              transform: translateY(-1px);
            }

            // 当禁用拖拽时，不显示拖拽效果
            &.sortable-disabled {
              cursor: default;

              &:hover {
                box-shadow: none;
                transform: none;
              }
            }
          }

          .arco-input-wrapper {
            background: #f2f3f5;
          }

          .img-drag-handle {
            top: 0 !important;
          }
        }

        .item-img-box {
          margin-right: 12px;
          position: relative;
          width: 133px;
          height: 100px;

          .item-img-dlete {
            position: absolute;
            padding: 8px;
            font-size: 32px;
            top: -16px;
            right: -16px;
            color: red;
            cursor: pointer;
          }
        }

        .small-img {
          margin: 0;
          height: 100px;
          object-fit: cover;
        }

        .item-right {
          padding-top: 24px;
        }
      }
    }
  }

  .drag-handle {
    padding: 4px;
    cursor: grab;
    padding: 4px;
    border-radius: 4px;

    &:hover {
      background-color: #f0f2f5;
    }

    &:active {
      cursor: grabbing;
    }

    .drag-icon {
      font-size: 16px;
      color: #86909c;
    }
  }
}

.draggable_box {
  margin-bottom: 25px;
  background: #f3f3f3;
  padding: 10px;
  position: relative;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  &:hover {
    transform: translateY(-2px);
  }
}
// :deep(.arco-input-wrapper) {
//   background-color: #ffffff;
// }
.item-title {
  padding: 12px 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  margin-top: 10px;
}
.item-img {
  height: 100px;
}
.seting-box {
  padding: 20px;
  background: #f0f2f5;
  border-radius: 3px;
  // .arco-input-wrapper {
  //   background: #ffffff;
  // }
}
.setting-content {
  .setting-header {
    padding-bottom: 12px;

    .header-title {
      width: 120px;
      padding-right: 12px;
      text-align: right;
    }
  }

  .setting-body {
    margin-top: 12px;

    .setting-item {
      position: relative;
      padding: 16px 12px;
      background: #f0f2f5;
      border-radius: 8px;
      margin-bottom: 20px;

      .btn-group {
        position: absolute;
        right: 0;
        top: 0;
        display: flex;
        align-items: center;
        padding: 4px;

        .btn-delete {
          padding: 4px;
          font-size: 24px;
          cursor: pointer;
        }
      }

      .item-name {
        font-size: 16px;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 1px solid #fff;
      }

      .item-title {
        padding: 12px 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }

      .arco-input-wrapper {
        background: #fff;
      }

      .item-button {
        position: relative;
        padding: 12px 8px 4px;
        background: #fff;
        border-radius: 4px;
        margin: 4px 0;
        transition: all 0.3s ease;

        &.draggable-item {          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
          }

          // 当禁用拖拽时，不显示拖拽效果
          &.sortable-disabled {
            cursor: default;

            &:hover {
              box-shadow: none;
              transform: none;
            }
          }
        }

        .arco-input-wrapper {
          background: #f2f3f5;
        }
      }

      // 拖拽相关样式
      .flip-list-move {
        transition: transform 0.5s;
      }

      .no-move {
        transition: transform 0s;
      }

      .ghost {
        opacity: 0.5;
        background: #c8ebfb;
      }

      .list-group {
        min-height: 20px;
      }

      .list-group-item {      }

      .list-group-item i {
        cursor: pointer;
      }

      .item-action {
        padding: 10px 0;

        .action-text {
          width: 150px;
          margin-right: 8px;
        }
      }

      .item-add-btn {
        display: inline-block;
        padding: 2px 8px;
        margin-top: 5px;
        font-size: 11px;
        color: #165dff;
        border-radius: 4px;
        font-weight: 600;
        border: 1px solid #165dff;
        cursor: pointer;
      }

      .item-img {
        margin-top: 12px;
        height: 160px;
      }

      .fit-content {
        width: fit-content;
      }

      .item-img-list {
        .img-list-item {
          margin: 4px 0;
          position: relative;
          padding: 8px;
          border-radius: 4px;
          transition: all 0.3s ease;
          background: #fff;
          border-radius: 4px;

          &.draggable-item {            &:hover {
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              transform: translateY(-1px);
            }

            // 当禁用拖拽时，不显示拖拽效果
            &.sortable-disabled {
              cursor: default;

              &:hover {
                box-shadow: none;
                transform: none;
              }
            }
          }

          .arco-input-wrapper {
            background: #f2f3f5;
          }

          .img-drag-handle {
            top: 0 !important;
          }
        }

        .item-img-box {
          margin-right: 12px;
          position: relative;
          width: 133px;
          height: 100px;

          .item-img-dlete {
            position: absolute;
            padding: 8px;
            font-size: 32px;
            top: -16px;
            right: -16px;
            color: red;
            cursor: pointer;
          }
        }

        .small-img {
          margin: 0;
          height: 100px;
          object-fit: cover;
        }

        .item-right {
          padding-top: 24px;
        }
      }
    }
  }

  .drag-handle {
    padding: 4px;
    cursor: grab;
    padding: 4px;
    border-radius: 4px;

    &:hover {
      background-color: #f0f2f5;
    }

    &:active {
      cursor: grabbing;
    }

    .drag-icon {
      font-size: 16px;
      color: #86909c;
    }
  }
}
.item-img {
  height: 100px;
}
.drag_top_box {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  display: flex;
  justify-content: space-between;
  padding: 8px;
  cursor: pointer;
  background-color: #f5f5f5;
  border-radius: 4px;

  &:hover {
    background-color: #e8e8e8;
  }
}
.btn_group {
  display: flex;
  margin-top: 20px;
}
</style>
